package com.gitee.fsadmin.common.support;

import com.gitee.fastmybatis.core.query.LambdaQuery;
import com.gitee.fastmybatis.core.support.Getter;
import com.gitee.fsadmin.common.context.UserContext;
import com.gitee.fsadmin.common.enums.IEnum;
import com.gitee.fsadmin.common.util.DateUtil;

import java.time.LocalDateTime;

public class MyLambdaQuery<E> extends LambdaQuery<E> {
    private static final long serialVersionUID = 5232128649485429495L;

    private static final String UPDATE_BY_FORMAT = "update_by = %s";
    private static final String UPDATE_TIME_FORMAT = "update_time = '%s'";

    public MyLambdaQuery(Class<E> entityClass) {
        super(entityClass);
    }

    @Override
    public LambdaQuery<E> eq(Getter<E, ?> getter, Object value) {
        if (value instanceof IEnum<?>) {
            return super.eq(getter, ((IEnum<?>) value).getValue());
        }
        return super.eq(getter, value);
    }

    @Override
    public LambdaQuery<E> notEq(Getter<E, ?> getter, Object value) {
        if (value instanceof IEnum<?>) {
            return super.notEq(getter, ((IEnum<?>) value).getValue());
        }
        return super.notEq(getter, value);
    }

    @Override
    public int update() {
        this.appendUpdate();
        return super.update();
    }

    @Override
    public int delete() {
        this.appendUpdate();
        return super.delete();
    }

    private void appendUpdate() {
        Long userId = UserContext.getUserId();
        if (userId != null) {
            this.setExpression(String.format(UPDATE_BY_FORMAT, userId));
        }
        this.setExpression(String.format(UPDATE_TIME_FORMAT, DateUtil.formatYmdhms(LocalDateTime.now())));
    }

}